package com.java.control.impl;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.java.common.ProductFileService;
import com.java.control.AbstractAdminFormController;
import com.java.entity.Product;
import com.java.service.ProductService;

/**
 * 产品添加
 * @author wqf
 * @version  Nov 23, 2011 1:10:42 PM
 */
public class ProductEditController extends AbstractAdminFormController{

	public ProductEditController(){
		this.setCommandClass(Product.class);
	}
		
	protected void addSubmit(HttpServletRequest request,HttpServletResponse response, Object command, BindException errors) throws Exception {
		Product product = (Product)command;
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("productImage");
		if (!file.isEmpty()) {
//			String realPath = request.getSession().getServletContext().getRealPath("/");
			String imageName = ProductFileService.Product.upload(file.getInputStream(),file.getOriginalFilename());
			product.setImageUri(imageName);
		}
		this.productService.editProduct(product);
		request.setAttribute("operation", "add");
	}	
	
	protected void modifySubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException errors) throws Exception{		
		Product product = (Product)command;
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("productImage");
		if (null!=file && !file.isEmpty()) {
//			String realPath = request.getSession().getServletContext().getRealPath("/");
			String imageName = ProductFileService.Product.upload(file.getInputStream(),file.getOriginalFilename());
			product.setImageUri(imageName);
		}
		this.productService.editProduct(product);
		
		request.setAttribute("operation", "modify");
		request.setAttribute("id", product.getId());
	}
		
	protected Object getCommandDataForModify(HttpServletRequest request){
		Long id=Long.valueOf(request.getParameter("id"));
		Product product = this.productService.getProductById(id);
		
		return product;
	}
	
	protected Object getCommandDataForAdd(HttpServletRequest request) {
		Product product = new Product();
		
		return product;
	}
	
	
	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}
	
	public ProductService productService;

	
}
